package com.damon.g2048.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.animation.AnimationUtils;
import android.view.animation.GridLayoutAnimationController;
import android.widget.GridLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.damon.g2048.ConfigData;
import com.damon.g2048.R;
import com.damon.g2048.entity.Point;
import com.damon.g2048.log.ELog;
import com.damon.g2048.log.LogFactory;
import com.damon.g2048.utils.AppInit;
import com.damon.g2048.utils.IntentUtils;
import com.damon.g2048.utils.UIHelper;
import com.damon.g2048.view.AboutDialog;
import com.damon.g2048.view.AnimLayer;
import com.damon.g2048.view.Card;
import com.damon.g2048.view.HelpDialog;
import com.damon.g2048.view.WinDialog;

/**
 * 
 * @author damon.han
 * 
 */
public class MainActivity extends SherlockActivity {

	private static final int groupIdFirst = 1;// 按钮组id
	private static final int idRecord = 100;// 记录按钮的id
	private static final int idShare = 130;// 分享按钮的id
	private static final int idReGame = 120;// 重来按钮的id
	private boolean hasMeasured;// 是否测量-保证就测量一次
	private static final int GAMEVIEWMEASURED = 111;// gameview测量标志
	private int gameViewWidth;
	private int gameViewHeight;
	private Context context;
	private ELog elog;
	private TextView txtScore;// 当前分数
	private TextView txtMaxScore;// 最大分数
	private GridLayout gameView;
	private View mainRecordView;

	private AnimLayer viewAnimLayer;
	private int maxScore = 0;
	private int score = 0;// 当前的分数
	SharedPreferences sp = null;
	private boolean isExit = false;
	private Card[][] cards = new Card[4][4];
	private List<Point> emptyPoint = new ArrayList<Point>();

	private Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case GAMEVIEWMEASURED:// 测量之后增加card
				int min = Math.min(gameViewWidth, gameViewHeight);
				int width = (min - UIHelper.dip2px(context, 10) * (ConfigData.LINES) * 2) / ConfigData.LINES;
				ConfigData.CARD_WIDTH = width;// 正方形
				addCards(ConfigData.CARD_WIDTH, ConfigData.CARD_WIDTH);// 正方形的卡片
				startGame();
				break;
			default:
				break;
			}
			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_Sherlock_Light);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.context = this;
		elog = LogFactory.createLog();
		initView();
		initData();
		initListener();
		addAd();
	}

	private void initView() {
		gameView = (GridLayout) findViewById(R.id.main_game_view);
		gameView.setColumnCount(ConfigData.LINES);
		gameView.setRowCount(ConfigData.LINES);
		viewAnimLayer = (AnimLayer) findViewById(R.id.main_animlayer);
		txtScore = (TextView) findViewById(R.id.txt_score);
		txtMaxScore = (TextView) findViewById(R.id.txt_max_score);
		mainRecordView = (View) findViewById(R.id.main_record_view);
	}

	/**
	 * 设置广告
	 */
	private void addAd() {
		AppInit.initAdd(this);
		// 设置迷你广告背景颜色
	}

	/**
	 * 
	 * @Description: 初始化数据
	 * @param
	 * @return void
	 * @throws
	 */

	private void initData() {
		elog = LogFactory.createLog();
		sp = getSharedPreferences(getResources().getString(R.string.pre_max_score), Activity.MODE_PRIVATE);
		maxScore = sp.getInt(getResources().getString(R.string.pre_max_score), 0);
		txtScore.setText(score + "");
		txtMaxScore.setText(maxScore == 0 ? "无" : (maxScore + ""));

		// 获得gameView的宽度和高度

		ViewTreeObserver vto = gameView.getViewTreeObserver();
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {
				if (hasMeasured == false) {
					// 先测量宽度和高度
					gameViewHeight = gameView.getMeasuredHeight();
					gameViewWidth = gameView.getMeasuredWidth();
					// 获取到宽度和高度后，可用于计算
					Message msg = handler.obtainMessage();
					msg.what = GAMEVIEWMEASURED;
					handler.sendMessageDelayed(msg, 100);
					hasMeasured = true;
				}
				return true;
			}
		});
	}

	private void initListener() {
		gameView.setOnTouchListener(new OnTouchListener() {
			private float startX, startY, offsetX, offsetY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startX = event.getX();
					startY = event.getY();
					break;
				case MotionEvent.ACTION_UP:
					offsetX = event.getX() - startX;
					offsetY = event.getY() - startY;
					if (Math.abs(offsetX) > Math.abs(offsetY)) {// x方向上的偏移大于y方向上的偏移
						if (offsetX < -ConfigData.swipMinDistance) {// 向左
							swipLeft();
						} else if (offsetX > ConfigData.swipMinDistance) {// right
							swipRight();
						}
					} else {
						if (offsetY < -ConfigData.swipMinDistance) {// 向上
							swipUp();
						} else if (offsetY > ConfigData.swipMinDistance) {// 向下
							swipDown();
						}
					}
					break;
				}
				return true;// 返回true表示消费了此次动作
			}
		});
		mainRecordView.setOnClickListener(clickListener);
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.main_record_view:

				break;

			default:
				break;
			}
		}
	};

	/**
	 * 
	 * @Description: 退出程序
	 * @param
	 * @return void
	 * @throws
	 */
	private void exit() {
		elog.d("exit");
		this.finish();
	}

	@Override
	/**
	 * 退出
	 */
	protected void onStop() {
		updateMaxScore();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// 释放资源，原finalize()方法名修改为close()
		elog.d("onDestroy");
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	/**
	 * 
	 * @Description: 更新最高分
	 * @param
	 * @return void
	 * @throws
	 */
	private void updateMaxScore() {
		SharedPreferences.Editor editor = sp.edit();
		if (score >= maxScore) {
			maxScore = score;
		}
		editor.putInt(getResources().getString(R.string.pre_max_score), maxScore);
		editor.commit();
		txtMaxScore.setText(maxScore == 0 ? "无" : (maxScore + ""));
	}

	/**
	 * 清理分数
	 */
	public void clearScore() {
		score = 0;
		showScore();
	}

	/**
	 * 增加分数
	 * 
	 * @param score
	 */
	public void addScore(int s) {
		score += s;
		updateMaxScore();
		showScore();
	}

	/**
	 * 显示分数
	 * 
	 * @param score
	 */
	public void showScore() {
		txtScore.setText(score + "");
	}

	/**
	 * 初始化添加卡片
	 * 
	 * @param width
	 * @param height
	 */
	public void addCards(int width, int height) {
		Card c = null;
		for (int y = 0; y < ConfigData.LINES; y++) {
			for (int x = 0; x < ConfigData.LINES; x++) {
				c = new Card(context);
				c.setNum(0);
				gameView.addView(c, width, height);
				cards[x][y] = c;
			}
		}
	}

	/**
	 * 启动游戏
	 */
	private void startGame() {
		for (int y = 0; y < 4; y++) {
			for (int x = 0; x < 4; x++) {
				cards[x][y].setNum(0);
			}
		}
		addRandomNum();
		addRandomNum();
	}

	/**
	 * 添加随机数
	 */
	private void addRandomNum() {
		// 如果已经是2048，则游戏取得胜利添加随机数之前检查一次是不是已经胜利
		emptyPoint.clear();
		for (int y = 0; y < 4; y++) {// 逐行
			for (int x = 0; x < 4; x++) {
				if (cards[x][y].getNum() <= 0) {
					emptyPoint.add(new Point(x, y));
				}
			}
		}
		if (emptyPoint.size() > 0) {
			Point point = emptyPoint.remove((int) (Math.random() * emptyPoint.size()));
			cards[point.getX()][point.getY()].setAnimation(AnimationUtils.loadAnimation(context, R.anim.card_in));// 进入动画
			cards[point.getX()][point.getY()].setNum(Math.random() > 0.1 ? 2 : 4);// 2和4的个数比例是1比4
		}
	}

	/**
	 * 向左移动
	 */
	private void swipLeft() {
		elog.i("left");
		boolean merge = false;// 无动作不添加
		for (int y = 0; y < 4; y++) {
			for (int x = 0; x < 4; x++) {
				for (int x1 = x + 1; x1 < 4; x1++) {
					// 右边不为空
					if (cards[x1][y].getNum() > 0) {
						if (cards[x][y].getNum() <= 0) {// 左边为空
							viewAnimLayer.createMoveAnim(cards[x1][y], cards[x][y], x1, x, y, y);
							cards[x][y].setNum(cards[x1][y].getNum());
							cards[x1][y].setNum(0);
							x--;// 如果还有相同的则继续向左合并
							merge = true;
						} else if (cards[x][y].equals(cards[x1][y])) {// 左右两边相同
							viewAnimLayer.createMoveAnim(cards[x1][y], cards[x][y], x1, x, y, y);
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x1][y].setNum(0);
							addScore(cards[x][y].getNum());
							merge = true;
							// playSoundNew(1);
						}
						break;
					}
				}
			}
		}
		if (merge) {
			addRandomNum();
			gameOverOrNot();
		}
	}

	private void swipRight() {
		elog.i("right");
		boolean merge = false;// 无动作不添加
		for (int y = 0; y < 4; y++) {
			for (int x = 3; x >= 0; x--) {
				for (int x1 = x - 1; x1 >= 0; x1--) {
					// 右边不为空
					if (cards[x1][y].getNum() > 0) {
						if (cards[x][y].getNum() <= 0) {// 左边为空
							viewAnimLayer.createMoveAnim(cards[x1][y], cards[x][y], x1, x, y, y);
							cards[x][y].setNum(cards[x1][y].getNum());
							cards[x1][y].setNum(0);
							x++;// 如果还有相同的则继续向左合并
							merge = true;
						} else if (cards[x][y].equals(cards[x1][y])) {// 左右两边相同
							viewAnimLayer.createMoveAnim(cards[x1][y], cards[x][y], x1, x, y, y);
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x1][y].setNum(0);
							addScore(cards[x][y].getNum());
							merge = true;
						}
						break;
					}
				}
			}
		}
		if (merge) {
			addRandomNum();
			gameOverOrNot();
		}
	}

	/**
	 * 向上
	 */
	private void swipUp() {
		elog.i("up");
		boolean merge = false;// 无动作不添加
		for (int x = 0; x < 4; x++) {
			for (int y = 0; y < 4; y++) {
				for (int y1 = y + 1; y1 < 4; y1++) {
					// 右边不为空
					if (cards[x][y1].getNum() > 0) {
						if (cards[x][y].getNum() <= 0) {// 左边为空
							viewAnimLayer.createMoveAnim(cards[x][y1], cards[x][y], x, x, y1, y);
							cards[x][y].setNum(cards[x][y1].getNum());
							cards[x][y1].setNum(0);
							y--;// 如果还有相同的则继续向左合并
							merge = true;
						} else if (cards[x][y].equals(cards[x][y1])) {// 左右两边相同
							viewAnimLayer.createMoveAnim(cards[x][y1], cards[x][y], x, x, y1, y);
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x][y1].setNum(0);
							addScore(cards[x][y].getNum());
							merge = true;
						}
						break;
					}
				}
			}
		}
		if (merge) {
			addRandomNum();
			gameOverOrNot();
		}
	}

	/**
	 * 向下
	 */
	private void swipDown() {
		elog.i("down");
		boolean merge = false;// 无动作不添加
		for (int x = 0; x < 4; x++) {
			for (int y = 3; y >= 0; y--) {
				for (int y1 = y - 1; y1 >= 0; y1--) {
					// 右边不为空
					if (cards[x][y1].getNum() > 0) {
						if (cards[x][y].getNum() <= 0) {// 左边为空
							viewAnimLayer.createMoveAnim(cards[x][y1], cards[x][y], x, x, y1, y);
							cards[x][y].setNum(cards[x][y1].getNum());
							cards[x][y1].setNum(0);
							y++;// 如果还有相同的则继续向左合并
							merge = true;
						} else if (cards[x][y].equals(cards[x][y1])) {// 左右两边相同
							viewAnimLayer.createMoveAnim(cards[x][y1], cards[x][y], x, x, y1, y);
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x][y1].setNum(0);
							addScore(cards[x][y].getNum());
							merge = true;
						}
						break;
					}
				}
			}
		}
		if (merge) {
			addRandomNum();
			gameOverOrNot();
		}
	}

	/**
	 * 判断游戏是否结束
	 * 
	 * @return int
	 *         <p>
	 *         100-结束
	 *         <p>
	 *         200-胜利
	 *         <p>
	 *         300继续
	 */
	private int checkComplete() {
		int isFinish = 100;
		for (int y = 0; y < 4; y++) {
			for (int x = 0; x < 4; x++) {
				// 如果已经是2048，则游戏取得胜利
				if (cards[x][y].getNum() >= 2048) {
					return 200;
				}
				if (cards[x][y].getNum() == 0 || (x > 0 && cards[x][y].equals(cards[x - 1][y])) || (x < 3 && cards[x][y].equals(cards[x + 1][y])) || (y > 0 && cards[x][y].equals(cards[x][y - 1])) || (y < 3 && cards[x][y].equals(cards[x][y + 1]))) {
					isFinish = 300;
					return isFinish;
				}
			}
		}
		return isFinish;
	}

	/**
	 * 游戏是否结束
	 */
	private void gameOverOrNot() {
		int result = checkComplete();
		switch (result) {
		case ConfigData.FLAG_OVER:
			newAlert(getResources().getString(R.string.msg_game_title), getResources().getString(R.string.msg_game_over_fail), getResources().getString(R.string.msg_game_restart), getResources().getString(R.string.msg_game_quit));
			break;
		case ConfigData.FLAG_WIN:
			final WinDialog win = new WinDialog(context);
			win.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(R.string.msg_game_restart), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					clearScore();// 清空分数
					startGame();
					win.dismiss();
				}
			});
			win.setButton(AlertDialog.BUTTON_NEGATIVE, getResources().getString(R.string.msg_game_quit), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					clearScore();// 清空分数
					finish();
				}
			});
			win.show();
			break;
		case ConfigData.FLAG_GON:// 继续
			break;
		}
	}

	/**
	 * 结束之后的对话框
	 */
	private void newAlert(String title, String message, String pButton, String nButton) {
		new AlertDialog.Builder(context).setTitle(title).setMessage(message).setPositiveButton(pButton, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				clearScore();// 清空分数
				startGame();
			}
		}).setNegativeButton(nButton, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		}).show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!isExit) {
				isExit = true;
				Toast.makeText(getApplicationContext(), R.string.RepeatBackKeyToExit, Toast.LENGTH_SHORT).show();
				new Handler().postDelayed(new Runnable() {
					public void run() {
						// 超时两秒之后退出状态改为false
						isExit = false;
					}
				}, 2000);
				return false;
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 分享
	 */
	private void share() {
		Intent intent = IntentUtils.getShareIntent();
		startActivity(Intent.createChooser(intent, getTitle()));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		LogFactory.createLog().e(item.getItemId());
		switch (item.getItemId()) {
		case idRecord:// 记录

			break;
		case idReGame:// 重新开始游戏
			reGame();
			break;
		case idShare:
			share();
			break;
		case R.id.action_quit:// 第一个
			exit();
			break;
		case R.id.action_help:// 帮助
			new HelpDialog(context).show();
			break;
		case R.id.action_about:// 关于
			new AboutDialog(context).show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 重新开始
	 */
	private void reGame() {
		AlertDialog.Builder builder = new AlertDialog.Builder(context).setIcon(R.drawable.ic_launcher).setTitle(context.getText(R.string.app_name) + AppInit.getVersionName(context));
		builder.setMessage("确定要重新开始游戏吗?");
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		builder.setPositiveButton("重新开始", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				clearScore();// 清空分数
				startGame();
			}
		});
		builder.show();
	}

	/**
	 * 生产菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// 放到点击分数的时候显示
		// menu.add(groupIdFirst, idRecord, 0,
		// "").setIcon(R.drawable.ic_compose)
		// .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM |
		// MenuItem.SHOW_AS_ACTION_WITH_TEXT);// 记录
		menu.add(groupIdFirst, idReGame, 1, "").setIcon(R.drawable.ic_refresh_inverse).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);// 重来
		menu.add(groupIdFirst, idShare, 2, getResources().getString(R.string.action_game_share)).setIcon(R.drawable.abs__ic_menu_share_holo_light).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);// 分享
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
